//
//  ListViewController.m
//  彩虹儿歌
//
//  Created by HelloWorld_L on 15/7/1.
//  Copyright (c) 2015年 HelloBaby. All rights reserved.
//

#import "ListViewController.h"
#import "MacroHeader.h"
#import "RequestManager.h"
#import "ListVCModel.h"
#import "ListTableVCell.h"
#import <UIImageView+WebCache.h>
#import <MediaPlayer/MediaPlayer.h>
#import "AppDelegate.h"

@interface ListViewController ()<RequestDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, retain) RequestManager *request;

@property (nonatomic, retain) UIView *headerView;

@property (nonatomic, retain) NSMutableDictionary *headerDic;
@property (nonatomic, retain) UITableView *mainTableView;
@property (nonatomic, retain) NSMutableArray *dataSourceArr;

@property (nonatomic, retain) MPMoviePlayerViewController *songMoviePlayer;

@property (nonatomic, retain) UIView *footerView;
@property (nonatomic, retain) UIButton *backBtn;

@end

@implementation ListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImageView *backgroundImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xiaohua01"]];
    [self.view addSubview:backgroundImgV];
    self.headerDic = [NSMutableDictionary dictionary];
    self.dataSourceArr = [NSMutableArray array];
    
    [self requestData];

    self.navigationItem.title = self.naviBarItemTitle;
    [self createMainTableView];
    [self createFooterView];
}


- (void)createMainTableView
{
    self.navigationItem.hidesBackButton = YES;
    
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.backgroundColor = [UIColor clearColor];
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView *backV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 4)];
    self.mainTableView.tableHeaderView = backV;
    
    [self.mainTableView registerClass:[ListTableVCell class] forCellReuseIdentifier:@"listTableVCell"];
    
    [self.view addSubview:self.mainTableView];
    [self.mainTableView release];
    

}

- (void)createHeaderView
{
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 4)];
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, (SCREEN_HEIGHT / 4) - 20, (SCREEN_HEIGHT / 4) - 20)];
    imgV.layer.cornerRadius = ((SCREEN_HEIGHT / 4) - 20) / 2;
    imgV.layer.masksToBounds = YES;
    [imgV sd_setImageWithURL:[NSURL URLWithString:[self.headerDic[@"icon"] objectForKey:@"url"]]];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_HEIGHT / 4), ((SCREEN_HEIGHT / 4) - 20) / 2, 220, 20)];
    titleLab.font = [UIFont systemFontOfSize:15];
    titleLab.text = self.headerDic[@"discription"];
    
    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    playBtn.frame = CGRectMake(SCREEN_WIDTH - 50, (SCREEN_HEIGHT / 4) - 50, 30, 30);
    [playBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang-3"] forState:UIControlStateNormal];
    
    [self.headerView addSubview:imgV];
    [self.headerView addSubview:titleLab];
    [self.headerView addSubview:playBtn];
    
    [imgV release];
    [titleLab release];
    
}

//底部的黑色导航条。
- (void)createFooterView
{
    self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 113, SCREEN_WIDTH, 49)];
    self.footerView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backBtn.frame = CGRectMake(20, 15, 20, 20);
    [self.backBtn setBackgroundImage:[UIImage imageNamed:@"zuojiantou16"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backTo:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.footerView addSubview:self.backBtn];
    [self.view addSubview:self.footerView];
    [self.footerView release];
}

- (void)backTo:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 数据请求

- (void)requestData
{
    self.request = [[RequestManager alloc] initWithRequestURL:[NSString stringWithFormat:@"http://app.beva.com/box-playlistItemData/p46/pl%@/kwerge--v2.0/page1-rp1000-signa46799eb25267398373e3d6c1ff08819.json",self.plistId] requestModel:GET parameter:nil];
    self.request.delegate = self;
    [self.request startRequest];
    [self.request release];
}

- (void)requestDidFinishWithData:(NSData *)data
{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                        options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
                                                          error:nil];
    NSDictionary *dataDic = dic[@"data"];
    NSDictionary *headerDic = dataDic[@"info"];
    self.headerDic = [headerDic mutableCopy];
    NSArray *listArr = dataDic[@"item"];
    for (NSDictionary *modelDic in listArr) {
        ListVCModel *model = [[ListVCModel alloc] init];
        [model setValuesForKeysWithDictionary:modelDic];
        [self.dataSourceArr addObject:model];
        [model release];
    }
    [self createHeaderView];
    [self.mainTableView reloadData];
    self.mainTableView.tableHeaderView = self.headerView;
}

- (void)requestError:(NSError *)error
{
    NSLog(@"%@",error);
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ListVCModel *model = self.dataSourceArr[indexPath.row];
    ListTableVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listTableVCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (81.0 / 108.0) * (SCREEN_WIDTH / 3) + 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *clearV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    clearV.backgroundColor = [UIColor clearColor];
    return clearV;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.songMoviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:[[(ListVCModel *)self.dataSourceArr[indexPath.row] mp4_720p] objectForKey:@"bcsurl"]]];
    self.songMoviePlayer.moviePlayer.scalingMode = MPMovieScalingModeNone;
    self.songMoviePlayer.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    [self.view addSubview:self.songMoviePlayer.view];
//    self.songMoviePlayer.view.frame = CGRectMake(50, 50, 220, 220);
//    [self setupMovie:self.songMoviePlayer.moviePlayer];
    [self presentMoviePlayerViewControllerAnimated:self.songMoviePlayer];
    [self.songMoviePlayer.moviePlayer play];
    
    CGFloat playerVF = SCREEN_WIDTH / 5;
    AppDelegate *apd = [UIApplication sharedApplication].delegate;
    apd.playerV.frame = CGRectMake(playerVF * 2, SCREEN_HEIGHT, playerVF, playerVF);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    
}

- (void)doFinished:(id)sender
{
    CGFloat playerVF = SCREEN_WIDTH / 5;
    AppDelegate *apd = [UIApplication sharedApplication].delegate;
    [UIView animateWithDuration:0.2 animations:^{
        apd.playerV.frame = CGRectMake(playerVF * 2, SCREEN_HEIGHT - playerVF - 20, playerVF, playerVF * 2);
    }];
    [UIView animateWithDuration:0.2 delay:0.2 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseOut animations:^{
        apd.playerV.frame = CGRectMake(playerVF * 2, SCREEN_HEIGHT - playerVF + 10, playerVF, playerVF * 2);
    } completion:nil];
    
    [UIView animateWithDuration:0.2 delay:0.4 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseOut  animations:^{
        apd.playerV.frame = CGRectMake(playerVF * 2, SCREEN_HEIGHT - playerVF, playerVF, playerVF * 2);
    } completion:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    [self.songMoviePlayer.view removeFromSuperview];
    [self.songMoviePlayer release];
    self.songMoviePlayer = nil;
}

//-(void)setupMovie:(MPMoviePlayerController *)myMovie
//{
//    CGRect aFrame = [[UIScreen mainScreen] applicationFrame];
//    aFrame = CGRectMake(0.0f, 0.0f, aFrame.size.height, aFrame.size.width);
//    
//    myMovie.controlStyle = MPMovieControlStyleDefault;
//    myMovie.view.frame = aFrame;
//    myMovie.view.center = CGPointMake(aFrame.size.width/2, aFrame.size.height/2);
//    CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI/2);
//    [myMovie.view setTransform:transform];
//    [[[[UIApplication sharedApplication] delegate] window] addSubview:myMovie.view];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
